<template>
  <div class="addClass">
    <a-modal v-model="addVisible" :title="title" @cancel="closeDialog">
      <div class="modal-box">
        <div class="search">
          <a-form-model :model="formData">
            <a-form-model-item label="* 所属学校">
              <a-select v-model="formData.school_name" style="width: 420px" placeholder="请选择所属学校" @change="handleSchoolChange">
                <a-select-option v-for="item in schoolData" :key="item.id" :value="item.id">{{ item.title }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="* 所属班级">
              <a-select v-model="formData.banji_name" style="width: 420px" placeholder="请选择所属班级" @change="handleBanjiChange">
                <a-select-option v-for="item in classData" :key="item.id" :value="item.id">{{ item.title }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </div>
        <a-transfer
          :data-source="dataSource"
          :target-keys="targetKeys"
          :show-search="showSearch"
          :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
          :show-select-all="false"
          @change="onChange">
          <template
            slot="children"
            slot-scope="{
              props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
              on: { itemSelectAll, itemSelect },
            }">
            <a-table
              :row-selection="
                getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
              "
              :columns="direction === 'left' ? leftColumns : rightColumns"
              :data-source="filteredItems"
              size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }"
              :custom-row="
                ({ key, disabled: itemDisabled }) => ({
                  on: {
                    click: () => {
                      if (itemDisabled || listDisabled) return;
                      itemSelect(key, !selectedKeys.includes(key));
                    },
                  },
                })
              "
            />
          </template>
        </a-transfer>
      </div>
      <template slot="footer">
        <div class="foot-btn">
          <span class="qxbtn" @click="closeDialog">取消</span>
          <span class="okbtn" @click="saveClassList">保存</span>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script>
import difference from 'lodash/difference';
const leftTableColumns = [
  {
    dataIndex: 'title',
    title: '学号',
  },
  {
    dataIndex: 'description',
    title: '姓名',
  },
];
const rightTableColumns = [
  {
    dataIndex: 'title',
    title: '学号',
  },
  {
    dataIndex: 'description',
    title: '姓名',
  },
];
export default {
  props: {
    addDialogVisible: {
      type: Boolean
    },
    schoolId: {
      default() {
        return 0
      }
    },
    classId: {
      default() {
        return 0
      }
    }
  },
  data() {
    return {
      addVisible: false,
      schoolData: [],
      classData: [],
      title: '添加名单',
      dataSource: [],
      targetKeys: [],
      disabled: true,
      showSearch: false,
      leftColumns: leftTableColumns,
      rightColumns: rightTableColumns,
      formData: {
        school_name: undefined,
        banji_name: undefined,
      },
      currentClassId: ''
    }
  },
  watch: {
    addDialogVisible(val) {
      this.dataSource = []
      this.targetKeys = []
      this.addVisible = val
      this.getSchoolList()
      if (this.schoolId) {
        this.getClassList(this.schoolId)
      }
      if (this.classId) {
        this.getBanjiList(this.classId)
      }
    },
    schoolId(val) {
      this.formData.school_name = val
    },
    classId(val) {
      this.formData.banji_name = val
      this.currentClassId = val
    }
  },
  methods: {
    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys;
      console.log(nextTargetKeys, 'nextTargetKeysnextTargetKeys');
      
    },
    triggerDisable(disabled) {
      this.disabled = disabled;
    },
    async getSchoolList() {
      const res = await this.$request.get('api/school/index');
      if (res.code === 1) {
        // console.log(res.data, 'res.datares.data');
        this.schoolData = res.data || [];
      }
    },
    handleSchoolChange(value) {
      console.log(`selected ${value}`);
      this.getClassList(value);
    },
    async getClassList(id) {
      const res = await this.$request.get(`api/school/banji_list?school_id=${id}`);
      if (res.code === 1) {
        console.log(res.data, 'res.datares.data');
        this.classData = res.data || [];
      }
    },
    handleBanjiChange(value) {
      console.log(`selected ${value}`);
      this.getBanjiList(value);
      this.currentClassId = value;
    },
    async getBanjiList(value) {
      const res = await this.$request.get(`api/school/banji_name_list?id=${value}`);
      if (res.code === 1) {
        this.dataSource = []
        this.targetKeys = []
        for (const item of res.data.unselected) {
          this.dataSource.push({
            key: item.user_id.toString(),
            title: item.no || '暂无',
            description: item.name || '暂无',
            disabled: false
          })
        }
        for (const item of res.data.selected) {
          this.dataSource.push({
            key: item.user_id.toString(),
            title: item.no || '暂无',
            description: item.name || '暂无',
            disabled: false
          })
          this.targetKeys.push(item.user_id.toString())
        }
      }
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    },
    saveClassList() {
      this.$request.post('api/school/banji_name_list_save', { id: this.currentClassId, user_ids: this.targetKeys.join(',') }).then(res => {
        if (res.code == 1) {
          this.$message.success(res.msg)
          this.addVisible = false;
          this.$emit('update:addDialogVisible', false);
          this.$emit('refresh');
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    closeDialog() {
      this.addVisible = false;
      this.$emit('update:addDialogVisible', false);
    }
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-modal-content{
  width: 1100px;
  // height: 234px;
  background: linear-gradient( 180deg, #DFF1FF 0%, #FFFFFF 100%);
  box-shadow: 0px 0px 8px 0px rgba(0,0,0,0.1);
  border-radius: 8px;
}
/deep/ .ant-modal-header{
  background: none;
  border-bottom: none;
  font-weight: 500;
  font-size: 18px;
  color: #000000;
}
/deep/ .ant-modal-footer{
  text-align: center;
  border-top: none;
}
/deep/ .ant-form-item{
    display: flex;
    justify-content: center;
}
/deep/ .ant-form{
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.foot-btn{
  display: flex;
  align-items: center;
  margin: 0 auto;
  width: 306px;
  padding-bottom: 45px;
}
.qxbtn{
  width: 134px;
  height: 40px;
  line-height: 40px;
  background: #EDF5FF;
  border-radius: 100px;
  border: 1px solid #A1C3FF;
  font-weight: 400;
  font-size: 16px;
  color: #0082FF;
  cursor: pointer;
}
.okbtn{
  width: 134px;
  height: 40px;
  line-height: 40px;
  background: linear-gradient( 90deg, #3881F8 0%, #5EA3FE 100%);
  border-radius: 100px;
  font-weight: 400;
  font-size: 16px;
  color: #FFFFFF;
  display: block;
  margin: 0 auto;
  cursor: pointer;
}
</style>